﻿using System;
using Castle.DynamicProxy;
using Sapit.Helpers;
using Sapit.Windsor.Attributes;

namespace Sapit.Windsor
{
    public class RetryInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            RetryAttribute retry = AttributeHelper.GetAttributeIfPresent<RetryAttribute>(invocation.Method);
            if (retry != null)
            {
                int numberOfTries = 0;
                bool success = false;
                while ((numberOfTries < retry.TimesToRetry || retry.TimesToRetry == 0) && (success == false))
                {
                    numberOfTries += 1;

                    try
                    {
                        invocation.ReturnValue = invocation.Method.Invoke(invocation.InvocationTarget, invocation.Arguments);
                        success = true;
                    }
                    catch (Exception)
                    {
                        if (numberOfTries == retry.TimesToRetry)
                        {
                            throw;
                        }
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
